package cn.edu.bupt.ch6_1.controller;

import cn.edu.bupt.ch6_1.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Tag(name = "redis操作示例")
@RestController
@RequestMapping("/api/v1/redis")
public class RedisDemoController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Operation(summary = "stringRedisTemplate value set", description = "stringRedisTemplate value set")
    @GetMapping(path = "/stringRedisTemplate/value/set", produces = "application/json")
    public Result<?> set(String key,String value) {
        stringRedisTemplate.opsForValue().set(key,value,60*5, TimeUnit.SECONDS);
        return Result.ok();
    }


    @Operation(summary = "stringRedisTemplate get", description = "stringRedisTemplate value get")
    @GetMapping(path = "/stringRedisTemplate/value/get", produces = "application/json")
    public Result<?> get(String key) {
        String value = stringRedisTemplate.opsForValue().get(key);
        return Result.ok(value);
    }


    @Operation(summary = "stringRedisTemplate set add", description = "stringRedisTemplate value set")
    @GetMapping(path = "/stringRedisTemplate/set/add", produces = "application/json")
    public Result<?> add(String key,String value) {
        stringRedisTemplate.opsForSet().add(key,value);
        stringRedisTemplate.expire(key,60 , TimeUnit.SECONDS);
        return Result.ok();
    }

    @Operation(summary = "stringRedisTemplate set members", description = "stringRedisTemplate value members")
    @GetMapping(path = "/stringRedisTemplate/set/members", produces = "application/json")
    public Result<?> members(String key) {
        Set set = stringRedisTemplate.opsForSet().members(key);//根据key获取set集合
        return Result.ok(set);
    }

    @Operation(summary = "RedisTemplate demo", description = "stringRedisTemplate value members")
    @GetMapping(path = "/redisTemplate/demo", produces = "application/json")
    public Result<?> demo() {
        //redisTemplate.setDefaultSerializer(new StringRedisSerializer());
        redisTemplate.opsForList().leftPush("demo", LocalTime.now());
        redisTemplate.expire("demo",60 , TimeUnit.SECONDS);

        List list = redisTemplate.opsForList().range("demo",0,100);
        return Result.ok(list);
    }
}
